package com.franklin.ideaplugin.api.utils;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Franklin
 * @since 2023/08/26 18:14
 */
public class DependencyUtils {

    public static List<VirtualFile> getModuleClassPath(Module module){
        ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
        VirtualFile[] roots = moduleRootManager.orderEntries().classes().getRoots();
        return Lists.newArrayList(roots);
    }

    public static List<VirtualFile> getProjectClassPath(Project project){
        Set<String> distinctSet = Sets.newHashSet();
        ModuleManager moduleManager = ModuleManager.getInstance(project);
        List<VirtualFile> virtualFileList = Arrays.stream(moduleManager.getModules())
                .map(DependencyUtils::getModuleClassPath)
                .flatMap(Collection::stream)
                .filter(virtualFile -> {
                    String canonicalPath = virtualFile.getCanonicalPath();
                    if (distinctSet.contains(canonicalPath)) {
                        return false;
                    }
                    distinctSet.add(canonicalPath);
                    return true;
                })
                .collect(Collectors.toList());

        return virtualFileList;
    }
}
